<template>
  <view class="page-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" color="#fff" size="20"></u-icon>
      </view>
      <text class="header-title">创建排班</text>
      <view class="header-right" @click="saveSchedule">
        <text class="save-text">保存</text>
      </view>
    </view>

    <!-- 排班表单 -->
    <scroll-view class="content-area" :scroll-y="true" :style="{ height: scrollHeight }">
      <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <!-- 排班人员 -->
        <view class="form-item">
          <text class="form-label">排班人员 *</text>
          <u-button 
            type="primary" 
            text="选择人员" 
            plain
            @click="selectStaff"
          ></u-button>
          <view v-if="selectedStaff.length > 0" class="selected-staff">
            <view 
              v-for="staff in selectedStaff" 
              :key="staff.id"
              class="staff-tag"
            >
              <text class="staff-name">{{ staff.name }}</text>
              <u-icon 
                name="close" 
                size="16" 
                color="#fff"
                @click="removeStaff(staff.id)"
              ></u-icon>
            </view>
          </view>
        </view>

        <!-- 排班日期 -->
        <view class="form-item">
          <text class="form-label">排班日期 *</text>
          <u-datetime-picker
            v-model="scheduleData.startDate"
            mode="date"
            :min-date="minDate"
            :max-date="maxDate"
            @change="handleStartDateChange"
          >
            <view class="picker-display">
              <text class="picker-text">{{ formatDate(scheduleData.startDate) }}</text>
              <u-icon name="calendar" color="#999" size="16"></u-icon>
            </view>
          </u-datetime-picker>
        </view>

        <!-- 排班周期 -->
        <view class="form-item">
          <text class="form-label">排班周期 *</text>
          <u-radio-group v-model="scheduleData.cycleType" @change="handleCycleChange">
            <u-radio 
              v-for="cycle in cycleOptions" 
              :key="cycle.value"
              :name="cycle.value"
              :label="cycle.label"
            ></u-radio>
          </u-radio-group>
        </view>

        <!-- 结束日期（周期排班时显示） -->
        <view v-if="scheduleData.cycleType === 'cycle'" class="form-item">
          <text class="form-label">结束日期 *</text>
          <u-datetime-picker
            v-model="scheduleData.endDate"
            mode="date"
            :min-date="scheduleData.startDate"
            :max-date="maxDate"
            @change="handleEndDateChange"
          >
            <view class="picker-display">
              <text class="picker-text">{{ formatDate(scheduleData.endDate) }}</text>
              <u-icon name="calendar" color="#999" size="16"></u-icon>
            </view>
          </u-datetime-picker>
        </view>
      </view>

      <!-- 班次设置 -->
      <view class="form-section">
        <view class="section-title">班次设置</view>
        
        <!-- 班次模板 -->
        <view class="form-item">
          <text class="form-label">班次模板</text>
          <u-button 
            type="info" 
            text="选择模板" 
            plain
            @click="selectTemplate"
          ></u-button>
          <view v-if="selectedTemplate" class="template-info">
            <text class="template-name">{{ selectedTemplate.name }}</text>
            <u-icon 
              name="close" 
              size="16" 
              color="#999"
              @click="clearTemplate"
            ></u-icon>
          </view>
        </view>

        <!-- 自定义班次 -->
        <view class="form-item">
          <text class="form-label">自定义班次</text>
          <u-button 
            type="success" 
            text="添加班次" 
            icon="plus"
            @click="addShift"
          ></u-button>
        </view>

        <!-- 班次列表 -->
        <view v-if="scheduleData.shifts.length > 0" class="shifts-list">
          <view 
            v-for="(shift, index) in scheduleData.shifts" 
            :key="index"
            class="shift-item"
          >
            <view class="shift-info">
              <text class="shift-name">{{ shift.name }}</text>
              <text class="shift-time">{{ shift.startTime }} - {{ shift.endTime }}</text>
            </view>
            <view class="shift-actions">
              <u-button 
                type="text" 
                text="编辑" 
                size="mini"
                @click="editShift(index)"
              ></u-button>
              <u-button 
                type="text" 
                text="删除" 
                size="mini"
                color="#ff4757"
                @click="removeShift(index)"
              ></u-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 排班规则 -->
      <view class="form-section">
        <view class="section-title">排班规则</view>
        
        <!-- 工作区域 -->
        <view class="form-item">
          <text class="form-label">工作区域</text>
          <u-button 
            type="primary" 
            text="选择区域" 
            plain
            @click="selectWorkArea"
          ></u-button>
          <view v-if="selectedWorkArea" class="area-info">
            <text class="area-name">{{ selectedWorkArea.displayName }}</text>
            <u-icon 
              name="close" 
              size="16" 
              color="#999"
              @click="clearWorkArea"
            ></u-icon>
          </view>
        </view>

        <!-- 排班备注 -->
        <view class="form-item">
          <text class="form-label">排班备注</text>
          <u-textarea
            v-model="scheduleData.remark"
            placeholder="请输入排班备注信息"
            :maxlength="200"
            :count="true"
          ></u-textarea>
        </view>
      </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <u-button 
        type="default" 
        text="取消" 
        @click="goBack"
      ></u-button>
      <u-button 
        type="primary" 
        text="保存并发布" 
        @click="saveAndPublish"
      ></u-button>
    </view>

    <!-- 班次编辑弹窗 -->
    <u-popup v-model="showShiftEdit" mode="center" :border-radius="20">
      <view class="shift-edit-popup">
        <view class="popup-header">
          <text class="popup-title">{{ editingShiftIndex >= 0 ? '编辑班次' : '添加班次' }}</text>
          <u-icon 
            name="close" 
            size="20" 
            color="#999"
            @click="closeShiftEdit"
          ></u-icon>
        </view>
        
        <view class="popup-content">
          <view class="form-item">
            <text class="form-label">班次名称 *</text>
            <u-input
              v-model="shiftForm.name"
              placeholder="请输入班次名称"
            ></u-input>
          </view>
          
          <view class="form-item">
            <text class="form-label">开始时间 *</text>
            <u-datetime-picker
              v-model="shiftForm.startTime"
              mode="time"
              @change="handleStartTimeChange"
            >
              <view class="picker-display">
                <text class="picker-text">{{ shiftForm.startTime }}</text>
                <u-icon name="clock" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">结束时间 *</text>
            <u-datetime-picker
              v-model="shiftForm.endTime"
              mode="time"
              @change="handleEndTimeChange"
            >
              <view class="picker-display">
                <text class="picker-text">{{ shiftForm.endTime }}</text>
                <u-icon name="clock" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
        </view>
        
        <view class="popup-actions">
          <u-button 
            type="default" 
            text="取消" 
            @click="closeShiftEdit"
          ></u-button>
          <u-button 
            type="primary" 
            text="确定" 
            @click="saveShift"
          ></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
/**
 * 创建排班页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0
 */

import { ref, reactive, onMounted } from 'vue'
import { regionApi } from '@/api/region'

// 页面高度计算
const scrollHeight = ref('calc(100vh - 200px)')

// 计算滚动视图高度
const calculateScrollHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    const windowHeight = systemInfo.windowHeight
    const statusBarHeight = systemInfo.statusBarHeight || 0
    const navbarHeight = 44 // 导航栏内容高度
    const bottomHeight = 80 // 底部按钮高度
    const padding = 16 // 上下边距
    
    // 计算实际可用高度
    const calculatedHeight = windowHeight - statusBarHeight - navbarHeight - bottomHeight - padding
    
    return `${calculatedHeight}px`
  } catch (error) {
    console.error('计算高度失败:', error)
    return 'calc(100vh - 200px)'
  }
}

// 响应式数据
const scheduleData = reactive({
  staffIds: [],
  startDate: new Date(),
  endDate: new Date(),
  cycleType: 'single', // single: 单日, cycle: 周期
  shifts: [],
  workAreaId: null,
  remark: ''
})

const selectedStaff = ref([])
const selectedTemplate = ref(null)
const selectedWorkArea = ref(null)
const showShiftEdit = ref(false)
const editingShiftIndex = ref(-1)

const shiftForm = reactive({
  name: '',
  startTime: '08:00',
  endTime: '16:00'
})

const minDate = ref(new Date())
const maxDate = ref(new Date(2025, 11, 31))

// 周期选项
const cycleOptions = ref([
  { value: 'single', label: '单日排班' },
  { value: 'cycle', label: '周期排班' }
])

// 班次模板数据
const shiftTemplates = ref([
  {
    id: 1,
    name: '标准早班',
    shifts: [
      { name: '早班', startTime: '08:00', endTime: '16:00' }
    ]
  },
  {
    id: 2,
    name: '标准晚班',
    shifts: [
      { name: '晚班', startTime: '16:00', endTime: '24:00' }
    ]
  },
  {
    id: 3,
    name: '三班倒',
    shifts: [
      { name: '早班', startTime: '08:00', endTime: '16:00' },
      { name: '中班', startTime: '16:00', endTime: '24:00' },
      { name: '夜班', startTime: '00:00', endTime: '08:00' }
    ]
  }
])

// 工作区域数据
const workAreas = ref([])
const loadingWorkAreas = ref(false)

// 方法
const goBack = () => {
  uni.navigateBack()
}

const saveSchedule = () => {
  if (!validateForm()) {
    return
  }
  
  uni.showLoading({ title: '保存中...' })
  
  // 模拟保存请求
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '排班保存成功',
      icon: 'success'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  }, 1000)
}

const saveAndPublish = () => {
  if (!validateForm()) {
    return
  }
  
  uni.showLoading({ title: '发布中...' })
  
  // 模拟发布请求
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '排班发布成功',
      icon: 'success'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  }, 1000)
}

const validateForm = () => {
  if (selectedStaff.value.length === 0) {
    uni.showToast({
      title: '请选择排班人员',
      icon: 'none'
    })
    return false
  }
  
  if (scheduleData.shifts.length === 0) {
    uni.showToast({
      title: '请添加班次信息',
      icon: 'none'
    })
    return false
  }
  
  return true
}

const selectStaff = () => {
  uni.navigateTo({ url: '/pages/property-work/staff-select' })
}

const removeStaff = (staffId) => {
  const index = selectedStaff.value.findIndex(staff => staff.id === staffId)
  if (index > -1) {
    selectedStaff.value.splice(index, 1)
  }
}

const handleStartDateChange = (date) => {
  scheduleData.startDate = date
}

const handleEndDateChange = (date) => {
  scheduleData.endDate = date
}

const handleCycleChange = (value) => {
  scheduleData.cycleType = value
}

const selectTemplate = () => {
  uni.showActionSheet({
    itemList: shiftTemplates.value.map(template => template.name),
    success: (res) => {
      const template = shiftTemplates.value[res.tapIndex]
      selectedTemplate.value = template
      scheduleData.shifts = [...template.shifts]
    }
  })
}

const clearTemplate = () => {
  selectedTemplate.value = null
  scheduleData.shifts = []
}

const addShift = () => {
  editingShiftIndex.value = -1
  shiftForm.name = ''
  shiftForm.startTime = '08:00'
  shiftForm.endTime = '16:00'
  showShiftEdit.value = true
}

const editShift = (index) => {
  editingShiftIndex.value = index
  const shift = scheduleData.shifts[index]
  shiftForm.name = shift.name
  shiftForm.startTime = shift.startTime
  shiftForm.endTime = shift.endTime
  showShiftEdit.value = true
}

const removeShift = (index) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个班次吗？',
    success: (res) => {
      if (res.confirm) {
        scheduleData.shifts.splice(index, 1)
      }
    }
  })
}

const selectWorkArea = () => {
  if (workAreas.value.length === 0) {
    loadWorkAreas()
    return
  }
  
  uni.showActionSheet({
    itemList: workAreas.value.map(area => area.displayName),
    success: (res) => {
      selectedWorkArea.value = workAreas.value[res.tapIndex]
      scheduleData.workAreaId = selectedWorkArea.value.zoneId
    }
  })
}

const clearWorkArea = () => {
  selectedWorkArea.value = null
  scheduleData.workAreaId = null
}

// 加载工作区域列表
const loadWorkAreas = async () => {
  if (loadingWorkAreas.value) {
    return
  }
  
  loadingWorkAreas.value = true
  uni.showLoading({ title: '加载中...' })
  
  try {
    // 使用统一的API服务层调用
    const response = await regionApi.getWorkAreas()
    
    if (response && response.code === 200) {
      workAreas.value = response.data || []
      uni.hideLoading()
      
      // 重新显示选择器
      uni.showActionSheet({
        itemList: workAreas.value.map(area => area.displayName),
        success: (res) => {
          selectedWorkArea.value = workAreas.value[res.tapIndex]
          scheduleData.workAreaId = selectedWorkArea.value.zoneId
        }
      })
    } else {
      // 错误消息处理规范：后端返回的message字段 > 后端返回的msg字段 > 前端自定义消息
      const errorMessage = response?.message || response?.msg || '加载工作区域失败'
      throw new Error(errorMessage)
    }
  } catch (error) {
    console.error('加载工作区域失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '加载工作区域失败',
      icon: 'none'
    })
  } finally {
    loadingWorkAreas.value = false
  }
}

const closeShiftEdit = () => {
  showShiftEdit.value = false
  editingShiftIndex.value = -1
}

const handleStartTimeChange = (time) => {
  shiftForm.startTime = time
}

const handleEndTimeChange = (time) => {
  shiftForm.endTime = time
}

const saveShift = () => {
  if (!shiftForm.name.trim()) {
    uni.showToast({
      title: '请输入班次名称',
      icon: 'none'
    })
    return
  }
  
  if (shiftForm.startTime >= shiftForm.endTime) {
    uni.showToast({
      title: '结束时间必须晚于开始时间',
      icon: 'none'
    })
    return
  }
  
  const shift = {
    name: shiftForm.name,
    startTime: shiftForm.startTime,
    endTime: shiftForm.endTime
  }
  
  if (editingShiftIndex.value >= 0) {
    scheduleData.shifts[editingShiftIndex.value] = shift
  } else {
    scheduleData.shifts.push(shift)
  }
  
  closeShiftEdit()
}

const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

onMounted(() => {
  // 计算页面高度
  scrollHeight.value = calculateScrollHeight()
  
  // 页面加载时初始化数据
  scheduleData.endDate = new Date(scheduleData.startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
})
</script>

<style scoped>
/* 页面容器规范 */
.page-container {
  min-height: 100vh;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 内容区域规范 */
.content-area {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.header-left, .header-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
}

.save-text {
  font-size: 28rpx;
  color: #fff;
}

.form-container {
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 20rpx;
}

.selected-staff {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 20rpx;
}

.staff-tag {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background-color: #667eea;
  border-radius: 20rpx;
}

.staff-name {
  font-size: 24rpx;
  color: #fff;
}

.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #eee;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.template-info,
.area-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-top: 20rpx;
}

.template-name,
.area-name {
  font-size: 28rpx;
  color: #333;
}

.shifts-list {
  margin-top: 20rpx;
}

.shift-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.shift-info {
  flex: 1;
}

.shift-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
}

.shift-time {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 8rpx;
}

.shift-actions {
  display: flex;
  gap: 10rpx;
}

.bottom-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.shift-edit-popup {
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  padding: 30rpx;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}
</style>
